//https://leetcode.cn/problems/zui-xiao-de-kge-shu-lcof/

class Solution {
public:
    vector<int> inventoryManagement(vector<int>& stock, int cnt) {
        srand(time(0));
        qsort(stock, 0, stock.size() - 1, cnt);
        vector<int> ret(stock.begin(), stock.begin() + cnt);
        return ret;

    }

    void qsort(vector<int>& nums, int l, int r, int cnt)
    {
        if (l >= r) return;

        //选取随机数
        int key = getrandom(nums, l, r);
        //数组分三块
        int i = l, left = l - 1, right = r + 1;
        while (i < right)
        {
            if (nums[i] < key) swap(nums[++left], nums[i++]);
            else if (nums[i] == key) i++;
            else swap(nums[--right], nums[i]);
        }

        int a = left - l + 1, b = right - left - 1;
        if (a > cnt) qsort(nums, l, left, cnt);
        else if (a + b >= cnt) return;
        else qsort(nums, right, r, cnt - a - b);
    }

    int getrandom(vector<int>& nums, int left, int right)
    {
        int r = rand();
        return nums[r % (right - left + 1) + left];
    }
};